<template>
	<div style="height:100%;">
		<div class="ctrls-bar">
			<div class="filter">
                <a-input-search v-model:value="keyword" style="width:200px;" @search="search" />
            </div>
			{{total}}部视频/
			<a-button type="primary" @click="editVisible=true">
				<upload-outlined></upload-outlined>
				添加视频
			</a-button>
		</div>

		<div class="list">
			<div class="item" v-for="item in list" :key="item.id">
				<a-card hoverable style="width: 300px;">
					<template #cover>
						<div style="padding:18px;">
							<img @click="visitVideo(item)"
								alt="example"
								v-if="item.thumb"
								:src="imgSiteUrl+item.thumb"
								style="width:262px;height:159px"
							/>
							<img @click="visitVideo(item)"
								alt="example"
								v-else
								src="~@/assets/album-cover.png"
							/>
						</div>
					</template>
					<template #actions>
						<span key="edit" @click="showEdit(item)"><edit-outlined />编辑</span>
						<span key="del" @click="deleteVideo(item.id)"><delete-outlined />删除</span>
					</template>
					<a-card-meta :title="item.title" :description="item.desc"></a-card-meta>
				</a-card>
			</div>
		</div>
		<div class="page">
			<a-pagination :current="currentPage" show-quick-jumper :total="total" @change="getList" :hideOnSinglePage="true" />
		</div>
	</div>

	<a-modal v-model:visible="editVisible" :title="waitingEdit?'编辑视频':'添加视频'" @cancel="cancelEdit" @ok="handleEdit" class="edit-video">
		
		<a-tabs v-model:activeKey="activeKey" :animated="false">
			<a-tab-pane key="1" tab="上传本地视频">
				<a-row>
					<a-col :span="4" class="label-name"><span class="red">*</span>视频名称</a-col>
					<a-col :span="20">
						<a-input v-model:value="formState.title" />
					</a-col>
				</a-row>
				<div class="blank"></div>
				<a-row>
					<a-col :span="4" class="label-name">视频描述</a-col>
					<a-col :span="20">
						<a-textarea v-model:value="formState.desc" />
					</a-col>
				</a-row>
				<div class="blank"></div>
				<a-row>
					<a-col :span="4" class="label-name"><span class="red">*</span>选择视频</a-col>
					<a-col :span="20">
						<a-upload action="n" :show-upload-list="false" @change="handleVideoPreview" :before-upload="handleVideo" accept=".mp4">
							<a-button type="primary" :ghost="formState.videoName?true:false">{{formState.videoName?formState.videoName:'选择本地视频'}}</a-button>
						</a-upload>
					</a-col>
				</a-row>
				<div class="blank"></div>
				<a-row>
					<a-col :span="4" class="label-name">视频封面</a-col>
					<a-col :span="20">
						<a-upload list-type="picture-card" action="n" :show-upload-list="false" @change="handlePreview" :before-upload="handleChangeBanner" accept=".png,.jpg">
							<div v-if="!formState.coverPreview" class="cover">
								<img src="@/assets/album-cover.png" alt="" />
								<div class="text">选择图片</div>
							</div>
							<div v-else class="cover">
								<img :src="formState.coverPreview" alt="" style="width:265px;height:138px" />
							</div>
						</a-upload>
					</a-col>
				</a-row>
			</a-tab-pane>
			<a-tab-pane key="2" tab="添加在线视频">
				<a-row>
					<a-col :span="4" class="label-name"><span class="red">*</span>视频名称</a-col>
					<a-col :span="20">
						<a-input v-model:value="onlineInfo.title" />
					</a-col>
				</a-row>
				<div class="blank"></div>
				<a-row>
					<a-col :span="4" class="label-name">视频描述</a-col>
					<a-col :span="20">
						<a-textarea v-model:value="onlineInfo.desc" />
					</a-col>
				</a-row>
				<div class="blank"></div>
				<a-row>
					<a-col :span="4" class="label-name"><span class="red">*</span>视频地址</a-col>
					<a-col :span="20">
						<a-input v-model:value="onlineInfo.url" />
					</a-col>
				</a-row>
				<div class="blank"></div>
				<a-row>
					<a-col :span="4" class="label-name">视频封面</a-col>
					<a-col :span="20">
						<a-upload list-type="picture-card" action="n" :show-upload-list="false" @change="handlePreview" :before-upload="handleChangeBanner" accept=".png,.jpg">
							<div v-if="!formState.coverPreview" class="cover">
								<img src="@/assets/album-cover.png" alt="" />
								<div class="text">选择图片</div>
							</div>
							<div v-else class="cover">
								<img :src="formState.coverPreview" alt="" style="width:265px;height:138px" />
							</div>
						</a-upload>
					</a-col>
				</a-row>
			</a-tab-pane>
		</a-tabs>
    </a-modal>

	<div class="player-wrap" v-show="playVisible" @click="playVisible=false;waitingPlay=null">
		<div class="player" v-if="waitingPlay&&waitingPlay.source===1" @click.stop>
			<video style="height:100%;width:100%" controls>
				<source :src="imgSiteUrl+waitingPlay.path" type="video/mp4">
			</video>
		</div>
		<div class="player" v-if="waitingPlay&&waitingPlay.source===2" @click.stop>
			<iframe frameborder="0" :src="waitingPlay.path" allowFullScreen="true" width="100%" height="100%"></iframe>
		</div>
	</div>

</template>

<script>
import { createVNode, defineComponent, onMounted, reactive, toRefs } from 'vue';
import { UploadOutlined, DeleteOutlined, EditOutlined,QuestionCircleOutlined} from '@ant-design/icons-vue';
import reqwest from 'reqwest';
import { messageTips } from '@/until/tools';
import Http from '@/until/http';
import config from '@/until/configs';
import { Modal } from 'ant-design-vue/lib';
function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
export default defineComponent({
	components:{UploadOutlined,DeleteOutlined,EditOutlined},
	setup() {
		const state = reactive({
			total:0,
			list:[],
			currentPage:1,
			manageStatus:false,
			editVisible:false,
			activeKey:'1',
			imgSiteUrl:config.imgSiteUrl,
			waitingEdit:null,
			playVisible:false,
			waitingPlay:null,
			keyword:''
		});

		const formState = reactive({
			title:'',
			desc:'',
			cover:'',
			coverPreview:'',
			videoFile:'',
			videoName:''
		});

		const onlineInfo = reactive({
			title:'',
			desc:'',
			url:'',
		});

		const cancelEdit = ()=>{
			Object.assign(formState,{
				title:'',
				desc:'',
				coverUrl:'',
				coverPreview:'',
				videoFile:'',
				videoName:''
			});
			Object.assign(onlineInfo,{
				title:'',
				desc:'',
				url:'',
				time:''
			});
			Object.assign(state,{
				waitingEdit:null
			});
			
		}

		const showEdit = (item)=>{
			Object.assign(state,{
				waitingEdit:item.id,
				editVisible:true
			})
			if(item.source===1) {
				Object.assign(state,{
					activeKey:'1'
				})
				Object.assign(formState,{
					title:item.title,
					desc:item.desc,
					coverUrl:'',
					coverPreview:item.thumb?state.imgSiteUrl+item.thumb:'',
					videoFile:'',
					videoName:item.path
				});
			} else {
				console.log(item)
				Object.assign(state,{
					activeKey:'2'
				})
				Object.assign(formState,{
					cover:'',
					coverPreview:item.thumb?state.imgSiteUrl+item.thumb:'',
				});
				Object.assign(onlineInfo,{
					title:item.title,
					desc:item.desc,
					url:item.path,
				})
			}
		}

		const handleEdit=()=>{
			const formData = new FormData();
			
			if(state.activeKey==='1') {
				if(formState.title.trim()==='') {
					messageTips('请填写视频名称',2);
					return false;
				}
				formData.append('file', formState.coverUrl);
				formData.append('video', formState.videoFile);
				formData.append('name', formState.title);
				formData.append('desc', formState.desc);
				formData.append('source', state.activeKey);
			} else {
				if(onlineInfo.title.trim()==='') {
					messageTips('请填写视频名称',2);
					return false;
				}
				if(onlineInfo.url.trim()==='') {
					messageTips('请填写视频地址',2);
					return false;
				}
				formData.append('file', formState.coverUrl);
				formData.append('url', onlineInfo.url);
				formData.append('name', onlineInfo.title);
				formData.append('desc', onlineInfo.desc);
				formData.append('source', state.activeKey);
			}			

			let path = config.baseUrl+'/admin/video/add';
			if(state.waitingEdit) {
				formData.append('id', state.waitingEdit);
				path = config.baseUrl+'/admin/video/edit';
			}
            reqwest({
                url: path,
                method: 'post',
                processData: false,
                data: formData,
                contentType : false,
                success: (res) => {
                    try{
                        let result = JSON.parse(res);
                        if(result.success) {
                            messageTips(result.message,3);
                            state.editVisible = false;
                            cancelEdit();
                            getList();
                        }
                    }catch(e) {
                        console.log(e)
                    }
                },
                error: (e) => {
                    if(e.status===401) {
                        messageTips('登录已过期',1);
                        setTimeout(()=>{
                            location.href = '/login';
                        },2000);
                    } 
                },
            });
		}
		

		const deleteVideo=(id)=>{
			Modal.confirm({
                title:'提示',
                icon: createVNode(QuestionCircleOutlined),
                content:'您确定要删除吗？',
                centered:true,
                okText:'确定',
                cancelText:'取消',
                onOk() {
                    Http.delVideo({id}).then(res=>{
                        if(res.success) {
                            messageTips(res.message,3);
                            getList(state.currentPage)
                        }
                    })
                }
            })
		}

		const visitVideo = (item)=>{
			Object.assign(state,{
				playVisible:true,
				waitingPlay:item
			})
		}


		const handlePreview= async ({file})=>{
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }
            formState.coverPreview = file.url || file.preview;
        }	

        const handleChangeBanner=(info)=>{
            formState.coverUrl = info;
        }

		const handleVideoPreview = ({file})=>{
			formState.videoName = file.name;
		}
		const handleVideo = (info)=>{
			formState.videoFile = info;
		}

		const getList = (page=1,keyword=state.keyword)=>{
			Http.getVideoList({page,title:keyword}).then(res=>{
				if(res) {
					Object.assign(state,{
						list:res.list,
						total:res.count
					});
				}
			});
		}

		const search = ()=>{
			getList();
		}

		onMounted(()=>{
			getList();
		})

		return {
			...toRefs(state),
			deleteVideo,
			handleEdit,
			formState,
			onlineInfo,
			handlePreview,
			handleChangeBanner,
			handleVideoPreview,
			handleVideo,
			showEdit,
			cancelEdit,
			visitVideo,
			search,
			getList
		}
	}
})
</script>

<style lang="scss" scoped>
@import '@/scss/video.scss';
</style>